package com.poizon.infrastructure.center.config.core.event.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.poizon.infrastructure.center.config.core.value.dto.ConfigChangeDto;
import com.poizon.infrastructure.center.config.core.value.dto.ConfigChangeEventDto;
import com.poizon.infrastructure.common.util.YamlToPropertiesConverter;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Executor;

import static com.poizon.infrastructure.common.util.StringToPropertiesConverter.convertStringToProperties;

/**
 * 配置中心/配置中心操作抽象
 */
@Slf4j
public abstract class AbstractChangeListener {
    public Executor getExecutor() {
        return getExecutorImpl();
    }

    /**
     * nacos专用
     */
    public void receiveConfigInfo(String configInfo) {
        log.info(">监听到nacos配置变更");

        if (StrUtil.isBlank(configInfo)) {
            return;
        }
        // 如果包含=properties
        Properties properties = new Properties();
        if (configInfo.contains("=")) {
            properties = convertStringToProperties(configInfo);
        }

        // 如果包含:yml
        if (configInfo.contains(":")) {
            properties = YamlToPropertiesConverter.convertYmlStringToProperties(configInfo);
        }

        // 处理成kv形式
        handlerConfigInfoImpl(properties);
    }

    /**
     * apollo专用
     */
    public void onChange(ConfigChangeEventDto configChangeEventDto) {
        log.info(">监听到apollo配置变更");
        Set<String> changedKeys = configChangeEventDto.changedKeys();
        if (CollUtil.isEmpty(changedKeys)) {
            return;
        }

        Properties properties = new Properties();

        changedKeys.stream().forEach(key -> {
            ConfigChangeDto change = configChangeEventDto.getChange(key);
            if (change == null) {
                return;
            }
            String value = change.getNewValue();
            properties.setProperty(key, value);
        });

        handlerConfigInfoImpl(properties);
    }

    protected abstract Executor getExecutorImpl();

    protected abstract void handlerConfigInfoImpl(Properties properties);
}
